package bb.lanxing.mvp.model;

import android.text.TextUtils;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
//import com.orm.SugarRecord;
//import com.orm.SugarTransactionHelper;

import org.litepal.LitePal;

import bb.lanxing.App;
import bb.lanxing.common.config.ImagePostfix;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.LaunchBanner;
import bb.lanxing.model.database.Province;
import bb.lanxing.mvp.model.i.ILaunchBannerModel;
import bb.lanxing.service.DownloadService;
import java.io.File;
import java.util.List;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class LaunchBannerModelImpl implements ILaunchBannerModel {
    @Override
    public List<LaunchBanner> getValidBanner() {
        long currentTimeMillis = System.currentTimeMillis();
        String curTime = String.valueOf(currentTimeMillis);

        List<LaunchBanner> l = LitePal.where("startTime<=? and endTime>?", curTime, curTime).order("showTime ASC, createTime DESC").find(LaunchBanner.class);

        return l;

//        return SugarRecord.find(LaunchBanner.class, "START_TIME<=? and END_TIME>?", new String[]{String.valueOf(currentTimeMillis), String.valueOf(currentTimeMillis)}, null, "SHOW_TIME ASC, CREATE_TIME DESC", null);
    }

    @Override
    public void updateLaunchBanner(final List<LaunchBanner> list) {
//        final List listAll = SugarRecord.listAll(LaunchBanner.class);
        List<LaunchBanner> listAll = LitePal.findAll(LaunchBanner.class);

        try{
            LitePal.beginTransaction();

            for (LaunchBanner launchBanner : listAll) {
                LaunchBanner findBanner = LaunchBannerModelImpl.this.findBanner(list, launchBanner);
                if (findBanner == null) {
                    LaunchBannerModelImpl.this.deleteImage(launchBanner);
                    launchBanner.delete();
                } else {
                    if (!TextUtils.equals(findBanner.getImageUrl(), launchBanner.getImageUrl())) {
                        LaunchBannerModelImpl.this.deleteImage(launchBanner);
                    }
                    findBanner.setShowTime(launchBanner.getShowTime());
                    findBanner.setLaunchCount(launchBanner.getLaunchCount());
                    findBanner.setId(launchBanner.getId());
                }
            }
            for (LaunchBanner launchBanner2 : list) {
                launchBanner2.save();
            }

            LitePal.setTransactionSuccessful();
        }
        catch (Exception e){

        }
        finally {
            LitePal.endTransaction();
        }



//        SugarTransactionHelper.doInTansaction(new SugarTransactionHelper.Callback() {
//            @Override
//            public void manipulateInTransaction() {
//                for (LaunchBanner launchBanner : listAll) {
//                    LaunchBanner findBanner = LaunchBannerModelImpl.this.findBanner(list, launchBanner);
//                    if (findBanner == null) {
//                        LaunchBannerModelImpl.this.deleteImage(launchBanner);
//                        launchBanner.delete();
//                    } else {
//                        if (!TextUtils.equals(findBanner.getImageUrl(), launchBanner.getImageUrl())) {
//                            LaunchBannerModelImpl.this.deleteImage(launchBanner);
//                        }
//                        findBanner.setShowTime(launchBanner.getShowTime());
//                        findBanner.setLaunchCount(launchBanner.getLaunchCount());
//                        findBanner.setId(launchBanner.getId());
//                    }
//                }
//                for (LaunchBanner launchBanner2 : list) {
//                    launchBanner2.save();
//                }
//            }
//        });


    }

    public void deleteImage(LaunchBanner launchBanner) {
        File bannerImageFile = launchBanner.getBannerImageFile();
        if (bannerImageFile == null || !bannerImageFile.exists()) {
            return;
        }
        bannerImageFile.delete();
    }

    @Override
    public void requestProvinceId(double d, double d2) {
        Observable.just(new LatLng(d, d2)).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<LatLng>() {
            @Override
            public void call(LatLng latLng) {
                final GeoCoder newInstance = GeoCoder.newInstance();
                newInstance.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        ReverseGeoCodeResult.AddressComponent addressDetail;
                        newInstance.destroy();
                        if (reverseGeoCodeResult == null || (addressDetail = reverseGeoCodeResult.getAddressDetail()) == null) {
                            return;
                        }
                        long provinceIdByName = Province.getProvinceIdByName(addressDetail.province);
                        if (provinceIdByName <= 0) {
                            return;
                        }
                        SharedManager.getInstance().setValue(SharedManager.KEY_LASTET_PROVINCE_ID, provinceIdByName);
                    }
                });
                newInstance.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            }
        });
    }

    public LaunchBanner findBanner(List<LaunchBanner> list, LaunchBanner launchBanner) {
        for (LaunchBanner launchBanner2 : list) {
            if (launchBanner.getServerId() == launchBanner2.getServerId()) {
                return launchBanner2;
            }
        }
        return null;
    }

    @Override
    public void downloadBannerImage(LaunchBanner launchBanner) {
        File bannerImageFile = launchBanner.getBannerImageFile();
        if (bannerImageFile == null) {
            return;
        }
        String imageUrl = launchBanner.getImageUrl();
        if (bannerImageFile.exists() && bannerImageFile.length() <= 0) {
            bannerImageFile.delete();
            download(imageUrl, bannerImageFile);
        } else if (bannerImageFile.exists()) {
        } else {
            download(imageUrl, bannerImageFile);
        }
    }

    private void download(String str, File file) {
        int lastIndexOf = str.lastIndexOf("!");
        if (lastIndexOf != -1) {
            str = str.substring(0, lastIndexOf);
        }
        App context = App.getContext();
        DownloadService.download(context, null, str + ImagePostfix.CDN_IMAGE_TYPE_LUNCH_IMAGE_GENERAL, file.getAbsolutePath());
    }
}
